<?php

namespace app\live\controller;

use app\common\model\live\GoodsModel;
use app\common\model\live\MallModel;
use app\common\model\live\PayModel;
use app\common\model\live\RoomModel;
use app\common\model\MemberModel;
use wechat\Factory;

class MallController extends BaseController
{
  private $roomModel;
  private $mallModel;
  private $goodsModel;
  private $roomLogin;
  private $payModel;
  private $wechat;
  private $memberModel;

  /**
   * 初始化
   */
  public function __construct()
  {
    parent::__construct();
    $this->roomModel = new RoomModel();
    $this->mallModel = new MallModel();
    $this->goodsModel = new GoodsModel();
    $this->memberModel = new MemberModel();
    $this->payModel = new PayModel();
    $this->roomLogin   = $this->getMemberLogin();
    $this->wechat      = Factory::officialAccount();
    $wxJsApi = $this->wechat->jssdk->buildConfig(['editAddress']);
    $this->assign('wx_js_api', $wxJsApi);
    $this->assign('room_login', $this->roomLogin);
  }

  /**
   * @throws \Exception
   */
  public function index()
  {
    if($this->request->isAjax()){
      $query = [];
      //$query[] = ['room_id','=',$roomId];
      $data = $this->getPage('live.Goods');
      $data['rows'] = empty($data['rows'])?[]:$this->goodsModel->_formatList($data['rows']);
      return $data;
    }
    $classId = $this->request->param('class_id');
    $roomId = $this->request->param('room_id/d');
    $roomInfo            = $this->roomModel->where('room_id', $roomId)->find();
    if(empty($roomInfo)) abort(500,'直播间不存在或已解散');
    $mallInfo = $this->mallModel->where('room_id',$roomId)->find();
    if(!empty($mallInfo)){
      $mallInfo['class_format'] = $this->getClass($mallInfo['class_ids']);
      $mallInfo['banner']          = json_decode($mallInfo['thumb'], true);
    }
    $playUrl             = $this->roomModel->getPlayUrl($roomId, $roomInfo['host_name']);
    $this->assign('mall_info',$mallInfo);
    $this->assign('room_info',$roomInfo);
    $this->assign('play_url',$playUrl);
    return $this->fetch();
  }

  /**
   * 格式化分类
   * @param $classIds
   * @return array
   */
  private function getClass($classIds){
    if(empty($classIds)) return [];
    $classIds = explode(',',$classIds);
    $arr = [];
    foreach($classIds as $k=>$v){
      $arr[$k]['value'] = $v;
    }
    return $arr;
  }

  /**
   * 商品详情页
   * @return string
   * @throws \Exception
   */
  public function goodsInfo()
  {
    return $this->fetch();
  }

  /*刷新订单*/
  public function orderRefresh(){
    $roomId = $this->request->param('room_id');
    $failTime = $this->mallModel->where('room_id',$roomId)->value('fail_time');
    $failTime = empty($failTime)?1800:$failTime*60;
    $this->payModel->where('room_id',$roomId)
        ->where('pay_type',3)
        ->where('is_pay',0)
        ->where('create_time','<',(time()-$failTime))
        ->update(['is_fail'=>1]);
    return true;
  }

}
